<style>
  tbody .table-namespace-col:hover {
    font-size: 1.2em;
  }

  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }

  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }

  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>

<template>
  <div class="news-table-con">
    <Table :columns="columns" :data="data" :loading="loading"></Table>

    <!-- 编辑 -->
    <Modal v-model="updateNewsModal.show" width="700" :mask-closable="false">

      <p slot="header" style="text-align:center">
        <Icon type="information-circled" style="margin-right: 5px;"></Icon>
        <span>编辑模块信息</span>
      </p>

      <div>
        <Form :model="updateNewsModal.form" label-position="left">
          <FormItem label="新闻编号" v-show="false">
            <Input v-model="updateNewsModal.form.id" style="width: 85%" disabled/>
          </FormItem>
          <FormItem label="* 发布日期">
            <Date-picker type="date" placeholder="选择日期" v-model="updateNewsModal.form.releaseDate"
                         style="width: 85%"></Date-picker>
          </FormItem>
          <FormItem label="* 新闻类型">
            <Select v-model="updateNewsModal.form.type" style="width: 85%">
              <Option v-for="newsType in newsTypeList" :key="newsType.id" :value="newsType.id">{{newsType.name}}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="* 新闻标题">
            <Input v-model="updateNewsModal.form.title" placeholder="请输入新闻标题" style="width: 85%"/>
          </FormItem>
          <FormItem label="* 封面图片">
            <div class="demo-upload-list" v-for="item in uploadList">
              <template v-if="item.status === 'finished'">
                <img :src="item.url">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                  <Icon type="ios-trash-outline" @click="handleRemove(item)"></Icon>
                </div>
              </template>
              <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
              </template>
            </div>
            <Upload
              name="upfile"
              :show-upload-list="false"
              :default-file-list="defaultUploadList"
              :on-success="handleSuccess"
              :format="['jpg','jpeg','png']"
              :max-size="5120"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload"
              type="drag"
              action="//updesignsz.com:8999/projectsImage"
              style="display: inline-block;width:58px;">
              <div style="width: 58px;height:58px;line-height: 58px;">
                <Icon type="camera" size="20"></Icon>
              </div>
            </Upload>
            <Modal title="查看图片" :transfer="false"  v-model="visibleModal.show" style="width: 500px; ">
              <img :src="imgName" style="width: 100%;">
            </Modal>
          </FormItem>
          <FormItem label="* 新闻内容">
            <br/>
            <div id="wangeditor">
              <div ref="editorElem" style="text-align:left;" v-model="updateNewsModal.form.content"></div>
            </div>
          </FormItem>
        </Form>
      </div>

      <div slot="footer">
        <Button type="primary" :loading="updateNewsModal.loading" @click="handleUpdateNews(updateNewsModal.form)"
                long>
          <span v-if="!updateNewsModal.loading">更新模块</span>
          <span v-else>更新请求提交中</span>
        </Button>
      </div>
    </Modal>

    <!-- 备注 -->
    <Modal v-model="updateSequenceModal.show" width="360" :mask-closable="false">

      <p slot="header" style="text-align:center">
        <Icon type="information-circled" style="margin-right: 5px;"></Icon>
        <span>编辑顺序</span>
      </p>

      <div style="text-align:center">

        <Input placeholder="请输入顺序" v-model="updateSequenceModal.sequence"/>
      </div>

      <div slot="footer">
        <Button type="primary" :loading="updateSequenceModal.loading"
                @click="handleUpdateSequence(updateSequenceModal.sequence)" long>
          <span v-if="!updateSequenceModal.loading">更新顺序</span>
          <span v-else>请求提交中</span>
        </Button>
      </div>
    </Modal>

    <!-- 删除 -->
    <Modal v-model="removeNewsModal.show" width="360">

      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="information-circled" style="margin-right: 5px;"></Icon>
        <span>确认删除模块</span>
      </p>

      <div style="text-align:center">
        <p>此操作将会导致相关模块及功能<b style="padding:0 5px;color: red;">不可用</b>，请确认是否删除？</p>
      </div>

      <div slot="footer">
        <Button type="text" @click="removeNewsModal.show=false">取消</Button>
        <Button type="error" :loading="removeNewsModal.loading" @click="handleRemoveNews(removeNewsModal.news)">
          <span v-if="!removeNewsModal.loading">确认删除</span>
          <span v-else>正在删除</span>
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import {mapState, mapActions} from 'vuex'
  import E from "wangeditor";


  export default {
    name: "NewsViewTable",
    props: ['data', 'loading'],
    data() {
      return {
        editor: null,
        editorContent: '',
        uploadList: [],
        defaultUploadList: [],
        imgName: '',
        visibleModal: {
          show:false
        },
        // 表格列配置
        columns: [
          {
            title: '新闻类型',
            key: 'typeName',
            align: 'center'
          },
          {
            title: '新闻标题',
            key: 'title',
            align: 'center'
          },
          {
            title: '新闻封面',
            key: 'coverThumbnail',
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('img', {
                  attrs: {
                    width: 60,
                    src: params.row.coverThumbnail
                  }
                }),
              ]);
            }
          },
          {
            title: '发布时间',
            key: 'releaseDate',
            align: 'center'
          },
          {
            title: '添加时间',
            key: 'createdDate',
            align: 'center'
          },
          {
            title: '顺序',
            key: 'sequence',
            align: 'center'
          },
          {
            title: '操作',
            width: 200,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.updateSequence(params.row)
                    }
                  }
                }, '顺序'),
                h('Button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.updateNews(params.row)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.removeNews(params.row)
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],

        // 更新模块模态框
        updateNewsModal: {
          show: false,
          form: {
            id: 0,
            title: '',
            type: '',
            cover: '',
            content: '',
            releaseDate: ''
          },
          loading: false
        },
        // 顺序更新模态框
        updateSequenceModal: {
          show: false,
          sequence: 0,
          id: 0,
          loading: false
        },

        // 模块删除模态框
        removeNewsModal: {
          show: false,
          news: {},
          loading: false
        }
      }
    },
    mounted() {
      this.editor = new E(this.$refs.editorElem);
      this.editor.customConfig.uploadImgServer = 'http://updesignsz.com:8999/uploadImage';
      this.editor.customConfig.uploadFileName = 'upfile';
      this.editor.customConfig.uploadImgTimeout = 100000000;
      // 编辑器的事件，每次改变会获取其html内容
      this.editor.customConfig.onchange = html => {
        this.editorContent = html;
//        this.catchData(this.editorContent); // 把这个html通过catchData的方法传入父组件
      };
      this.editor.customConfig.menus = [
        // 菜单配置
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'emoticon', // 表情
        'image', // 插入图片
        'table', // 表格
        'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ];
      this.editor.create();
    },
    computed: {
      ...mapState('news', {
        newsTypeList: state => state.type.typeList,
        newsData: state => state.news.news
      })
    },
    methods: {
      ...mapActions('news/type', [
        'listType'
      ]),
      ...mapActions('news/news', [
        'getNews'
      ]),
      // 更新模块
      updateNews(news) {
        this.getNews(news);
        this.uploadList = [];
        let updateNewsModal = this.updateNewsModal;
        this.editor.txt.html(this.newsData.content);
        let keys = Object.keys(news);
        keys.forEach(key => {
          updateNewsModal.form[key] = news[key];
        })
//        updateNewsModal.form.content = news.content;
        if (news.cover != undefined) {
          var _file = {};
          _file.name = '11';
          _file.url = news.cover;
          _file.status = 'finished';
          this.uploadList.push(_file);
          updateNewsModal.form.cover = news.cover;
        }
        updateNewsModal.form.type = news.typeEntity.id
        updateNewsModal.show = true;
      },
      // 更新投保人
      updateSequence(newsForm) {
        let updateSequenceModal = this.updateSequenceModal;
        updateSequenceModal.show = true
        updateSequenceModal.sequence = newsForm.sequence
        updateSequenceModal.id = newsForm.id
      },
      handleUpdateNews(newsForm) {
        let updateNewsModal = this.updateNewsModal;
        var cover = '';
        for (var i = 0; i < this.uploadList.length; i++) {
          cover += this.uploadList[i].url;
        }
        newsForm.cover = cover;
        newsForm.content = this.editorContent != '' ? this.editorContent : updateNewsModal.form.content;
        updateNewsModal.loading = true;
        this.$emit('on-update-news', newsForm, (status) => {
          if (status) {
            updateNewsModal.show = false;
            Object.assign(this.$data.updateNewsModal.form, this.$options.data().updateNewsModal.form)
          }
          updateNewsModal.loading = false;
        })
      },
      handleUpdateSequence(sequence) {
        let updateSequenceModal = this.updateSequenceModal;
        updateSequenceModal.loading = true
        let ss = {};
        ss.id = updateSequenceModal.id
        ss.sequence = sequence
        this.$emit('on-update-sequence', ss, (status) => {
          if (status) {
            updateSequenceModal.show = false
          }
          updateSequenceModal.loading = false
        })
      },


      // 删除新闻
      removeNews(news) {
        let removeNewsModal = this.removeNewsModal;
        removeNewsModal.show = true;
        removeNewsModal.news = news;
      },
      handleRemoveNews(news) {
        let removeNewsModal = this.removeNewsModal;
        removeNewsModal.loading = true;
        this.$emit('on-remove-news', news, (status) => {
          if (status) {
            removeNewsModal.show = false
            removeNewsModal.news = {}
          }
          removeNewsModal.loading = false
        })
      },
      handleView(name) {
        this.imgName = name;
        this.visibleModal.show = true;
      },
      handleRemove(file) {
//         从 upload 实例删除数据
        this.uploadList.splice(this.uploadList.indexOf(file), 1)
      },
      handleSuccess(res, file) {
        file.url = res.data.url;
        file.name = res.data.name;
        console.log(file);
        this.uploadList.push(file);
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: '超出文件大小限制',
          desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
        });
      },
      handleBeforeUpload() {
        const check = this.uploadList.length < 1;
        if (!check) {
          this.$Notice.warning({
            title: '最多只能上传 1 张图片。'
          });
        }
        return check;
      }
    },
    created() {
      this.listType();
      this.getNews(this.updateSequenceModal);
    }
  }
</script>


